package database.team.phase2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Index {
		public Index() throws IOException{
			String minimum = null, maximum = null, tuple;
			String absPathEmp,absPathDept;
			File fileEmp = new File("TableEmp");
			File fileDept = new File("TableDept");
			//Read all the tmp files from TableEmp and TableDept".
			absPathEmp = fileEmp.getAbsolutePath();
			File folderEmp = new File(absPathEmp);
			File[] tempFilesEmp = folderEmp.listFiles();
			absPathDept = fileDept.getAbsolutePath();
			File folderDept = new File(absPathDept);
			File[] tempFilesDept = folderDept.listFiles();
			FileWriter outputEmp = new FileWriter("EmpIndex.txt");
			PrintWriter empIndex = new PrintWriter(outputEmp); 
			FileWriter outputDept = new FileWriter("DeptIndex.txt");
			PrintWriter DeptIndex = new PrintWriter(outputDept); 

			for(int i=0; i < tempFilesEmp.length;i++){
				BufferedReader empl = new BufferedReader(new FileReader(tempFilesEmp[i]));
				try {
					minimum = empl.readLine().substring(0,7);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				while ((tuple = empl.readLine()) != null) {
					if (tuple != null) {
						maximum = tuple.substring(0,7);
					}
				}
				empIndex.println(minimum+maximum);
				
			}
			//Closing the writer
			empIndex.close();
			
			for(int j=0; j < tempFilesDept.length;j++){
				    BufferedReader dept = new BufferedReader(new FileReader(tempFilesDept[j]));
					try {
						minimum = dept.readLine().substring(0,7);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					while ((tuple = dept.readLine()) != null) {
						if (tuple != null) {
							maximum = tuple.substring(0,7);
						}
					}
					
				 DeptIndex.println(minimum+maximum);
			}
			//Closing the writer
			   DeptIndex.close();
	}

		
		public static void main(String[] args) throws IOException {
			 System.out.println("Generating indexes for Employee and Department");
			 long startTime = System.currentTimeMillis();
			 new Index();
			 long endTime = System.currentTimeMillis();
			 float totalTime = (endTime - startTime);
			 System.out.println("Total time to Create the indexes for tables Employee and Department: "+totalTime); 
			 System.out.println("The result is shown in the file EmpIndex.txt and DeptIndex.txt");
		 }
}